package org.phoenix.mall.admin.service.impl;

import org.phoenix.mall.admin.common.pojo.vo.RightVO;
import org.phoenix.mall.admin.mapper.RightMapper;
import org.phoenix.mall.admin.pojo.Right;
import org.phoenix.mall.admin.service.RightService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RightServiceImpl implements RightService {

    private RightMapper rightMapper;

    @Override
    public Right addRight(Right right) {
        rightMapper.insert(right);
        return right;
    }

    @Override
    public List<Right> getRightByPid(Integer pid) {
        Example example = new Example(Right.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("pid", pid);

        return rightMapper.selectByExample(example);
    }

    @Override
    public List<RightVO> getTreeRights() {
        return recursionRight(0);
    }

    @Override
    public List<RightVO> getListRights() {
        List<RightVO> targetRights = new ArrayList<>();
        List<Right> sourceRights = rightMapper.selectAll();
        RightVO target = null;
        for (Right source : sourceRights) {
            target = new RightVO();
            BeanUtils.copyProperties(source,target);
            targetRights.add(target);
        }
        return targetRights;
    }

    @Override
    public List<RightVO> getChildRightListByPid(Integer pid, Integer level) {
        List<RightVO> list = null;
        switch (level){
            case 1 :
                list = rightMapper.query2ChildRightListByPid(pid);
                break;
        }
        return list;
    }

    private List<RightVO> recursionRight(Integer pid){
        List<Right> sourceRights = getRightByPid(pid);
        List<RightVO> targetRights = null;
        if(sourceRights.size() > 0){
            targetRights  = new ArrayList<>();
            RightVO targetRight = null;
            List<RightVO> targetChildRights = null;
            for (Right item : sourceRights){
                targetRight = new RightVO();
                BeanUtils.copyProperties(item,targetRight);
                targetChildRights = recursionRight(item.getId());
                targetRight.setChildren(targetChildRights);

                targetRights.add(targetRight);
            }
        }

        return targetRights;
    }

    @Resource
    public void setRightMapper(RightMapper rightMapper) {
        this.rightMapper = rightMapper;
    }
}
